package api.interceptor;

import android.support.v4.util.ArrayMap;

import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2018-01-12.
 */

public class CommonParamsInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        String method = request.method();
        if (method.equals("GET")) {
            //get请求后面追加共同的参数
            HttpUrl httpUrl = request.url().newBuilder()
                    .addQueryParameter("version", "1.01")
                    .addQueryParameter("token", "122")
                    .addQueryParameter("device", "Android").build();
            request = request.newBuilder().url(httpUrl).build();
            return chain.proceed(request);
        } else if (method.equals("POST")) {
            //post请求追加参数 (提交数据的格式为表单)
            FormBody.Builder newBody = new FormBody.Builder();
            newBody.add("version", "1.01")
                    .add("token", "1.01").add("device", "Android").build();
            //拦截请求中用户传入的数据，把参数遍历放入新的body里面，然后进行一块提交
            FormBody oldBody = (FormBody) request.body();
            for (int i = 0; i < oldBody.size(); i++) {
                newBody.add(oldBody.encodedName(i), oldBody.encodedValue(i));
            }
            request = request.newBuilder().post(newBody.build()).build();
            return chain.proceed(request);

        }
        return chain.proceed(request);
    }
    public static class Post4JsonCustomParamsInterceptor implements Interceptor{
        private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            ArrayMap paramsMap = new ArrayMap();
            paramsMap.put("version", "1.0");
            paramsMap.put("token", "");
            paramsMap.put("device", "Android");
            if (request.body() instanceof FormBody)
            {
                FormBody oldBody = (FormBody) request.body();
                for (int i = 0; i < oldBody.size(); i++)
                {
                    paramsMap.put(oldBody.encodedName(i), oldBody.encodedValue(i));
                }
            }
            Gson gson = new Gson();
//            AppLog.i("Gson参数格式---" + gson.toJson(paramsMap));

            RequestBody body = RequestBody.create(JSON, gson.toJson(paramsMap));
            request = request.newBuilder().post(body).build();
            return chain.proceed(request);
        }
    }
}